import { fileURLToPath, URL } from 'node:url';
import { ConfigEnv, defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import UnoCSS from 'unocss/vite';

import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';

import VitePluginMetaEnv from 'vite-plugin-meta-env';
import { name as APP_NAME, version as APP_VERSION } from './package.json';
import dayjs from 'dayjs';

// https://vitejs.dev/config/
export default (configEnv: ConfigEnv) => {
  const { mode } = configEnv;
  const env = loadEnv(mode, process.cwd());

  const metaEnv = {
    APP_VERSION,
    APP_NAME,
    APP_BUILD_TIME: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  };

  return defineConfig({
    base: env.VITE_BASE_URL,
    plugins: [
      vue(),
      vueJsx(),
      UnoCSS(),
      AutoImport({
        resolvers: [ElementPlusResolver()],
        include: [
          /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
          /\.vue$/,
          /\.vue\?vue/, // .vue
          /\.md$/, // .md
        ],
        imports: ['vue', 'vue-router'],
        dts: './auto-imports.d.ts',
        injectAtEnd: true,
        eslintrc: {
          enabled: true,
          filepath: './.eslintrc-auto-import.json',
        },
      }),
      Components({
        resolvers: [ElementPlusResolver()],
      }),
      VitePluginMetaEnv(metaEnv, 'import.meta.env'),
      VitePluginMetaEnv(metaEnv, 'process.env'),
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
    server: {
      headers: {
        'Access-Control-Allow-Origin': '*',
      },
      cors: true,
      open: false,
      port: 5000,
      host: true,
      proxy: {
        '/api': {
          target: 'https://api.v4ocder.cn/',
          changeOrigin: true,
          rewrite: path => path.replace(/^\/api/, ''),
        },
        '/amap': {
          target: 'https://amap.v4ocder.cn/',
          changeOrigin: true,
          rewrite: path => path.replace(/^\/amap/, ''),
        },
      },
    },
  });
};
